import time
from datetime import datetime
import pymysql

def db(sql,param):
    #1.通过四大参数获取数据库连接
    con = pymysql.connect(host="localhost",port=3306,user="root",passwd="root",db="app_jrapp")
    #2.通过连接创建控制台
    cursor = con.cursor()
    #3.准备sql语句

    # #4.执行多条sql
    # cursor.executemany(sql,param)

    #4.1执行单条sql
    cursor.execute(sql,param)

    #提交
    con.commit()

    #6.关闭资源 数据库连接池
    cursor.close()
    con.close()

def switch_level(level):
    match level:
        case 'D':
            return 0
        case 'I':
            return 1
        case 'W':
            return 2
        case 'E':
            return 3
        case 'V':
            return 4
        case _:
            return 0

def convert_time(time_str):
    year = datetime.now().year
    full_time = f"{year}-{time_str}"
    dt = datetime.strptime(full_time, "%Y-%m-%d %H:%M:%S.%f")
    return dt.strftime("%Y-%m-%d %H:%M:%S")

def read_logs(file):
    #记录文件上次读取位置
    last_position = 0
    #移动到上次读取位置
    counts = [0, 0, 0, 0, 0]

    with open(file, 'r', encoding="utf-8") as f:
        while True:
            #移动到上次读取位置
            f.seek(last_position)

            for line in f:
                if not line.strip():
                    continue

                parts = line.strip().split(maxsplit=5)
                # print(parts)
                # print(len(parts))

                if len(parts) != 6:
                    continue #跳过格式不正确的行

                create_time = convert_time(parts[0]+" "+parts[1])
                log_level = parts[4]
                log_detail = parts[5]

                counts[switch_level(parts[4])] += 1
                log_count = counts[switch_level(parts[4])]

                sql = 'INSERT INTO	log_info (create_time, log_level, log_count, log_detail) VALUES(%s,%s,%s,%s)'
                param = [create_time, log_level, log_count, log_detail]
                db(sql,param)

            #更新上次读取位置
            last_position = f.tell()

        #等待两秒
        time.sleep(2)

if __name__ == '__main__':
    read_logs("jrapp.log")


